<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import?type=user')"
          >excel导入</el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDownloadExcel"
          >excel导出</el-button>
          <el-button
            icon="plus"
            type="primary"
            size="small"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px">
        <el-table v-loading="loading" border :data="list">
          <el-table-column
            label="序号"
            type="index"
            sortable
            :index="indexMethod"
            width="100"
          />
          <el-table-column label="头像" sortable prop="staffPhoto">
            <template #default="{ row }">
              <img
                v-imgerror="errorImg"
                class="staff"
                :src="row.staffPhoto || defaultPhoto"
                alt=""
                @click="handleImgClick(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable prop="username" />
          <el-table-column label="手机号" sortable prop="mobile" />
          <el-table-column label="工号" sortable prop="workNumber" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            :formatter="formatEmployment"
            sortable=""
          />
          <el-table-column label="部门" sortable prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry">
            <template #defalut="{ row }">
              {{ row.timeOfEntry | formtime("YYYY年MM月DD日") }}
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small">角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="del(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 4, 6, 8]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          /></div></el-card>
      <AddEmployee :show-dialog.sync="showDialog" />
      <el-dialog width="300px" title="二维码" :visible="showCodeDialog" @close="showCodeDialog=false">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployee } from '@/api/employees'
import AddEmployee from './components/AddEmployee.vue'
import obj from '@/constant/employees'
import dayjs from 'dayjs'
import errorImg from '@/assets/common/bigUserHeader.png'
import QrCode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    AddEmployee
  },
  data() {
    return {
      list: [],
      page: 1, // 当前页
      pageSize: 8, // 每页条数
      total: 0, // 总数
      loading: false,
      showDialog: false,
      defaultPhoto:
        'https://ts1.cn.mm.bing.net/th?id=OIP-C.VN5jjFb2UPyD4AM9X03vKAAAAA&w=176&h=170&c=8&rs=1&qlt=90&o=6&pid=3.1&rm=2',
      errorImg,
      showCodeDialog: false
    }
  },

  created() {
    this.getEmployeeList()
  },
  methods: {
    // 渲染
    async getEmployeeList() {
      this.loading = true
      const {
        data: { total, rows }
      } = await reqGetEmployeeList(this.page, this.pageSize)
      // console.log(res)
      this.list = rows
      this.total = total
      this.loading = false
      console.log(this.list)
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.page = 1
      this.getEmployeeList()
    },
    handleCurrentChange(val) {
      this.page = val
      this.getEmployeeList()
    },
    indexMethod(index) {
      return index + 1 + this.pageSize * (this.page - 1)
    },

    formatEmployment(row, column, cellValue, index) {
      const arr = obj.hireType.find((item) => item.id === cellValue)
      return arr ? arr.value : '未知'
      // console.log(row, column, cellValue, index)
    },
    // 删除
    del(id) {
      this.$confirm('确定删除该员工吗', '温馨提示')
        .then(async() => {
          await reqDelEmployee(id)
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.$message.success('删除成功')
          this.getEmployeeList()
        })
        .catch(() => {
          this.$message.success('取消')
        })
    },
    // 导出
    async handleDownloadExcel() {
      const headersArr = [
        '姓名',
        '手机号',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      const headersRelations = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }

      const {
        data: { rows }
      } = await reqGetEmployeeList(1, this.total)
      const dataArr = this.formatJson(rows, headersArr, headersRelations)
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      import('@/vendor/Export2Excel').then((excel) => {
        // console.log(excel)
        excel.export_json_to_excel({
          header: headersArr,
          data: dataArr,
          filename: '员工信息表',
          autoWidth: true,
          bookType: 'xlsx',
          multiHeader,
          merges
        })
      })
    },
    handleImgClick(url) {
      if (!url) return this.$message.error('请上传头像')
      this.showCodeDialog = true
      this.$nextTick(() => {
        // 如果这里 url 写的是网址, 就会跳转到对应网址 (二维码分享效果)
        QrCode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    formatJson(rows, headersArr, headersRelations) {
      // 外层数组得长度 => 有多少个小数组 => rows里面有多少个小数组
      // 内层数组长度=>headersArr里面有多少个数据  决定了 小数据中有几条数据
      const arr = []
      rows.forEach((item) => {
        const res = []
        headersArr.forEach((v) => {
          const enlishKey = headersRelations[v]
          let val = item[enlishKey]
          if (enlishKey === 'formOfEmployment') {
            const { hireType } = obj
            const resObj = hireType.find((item) => item.id === val)
            val = resObj ? resObj.value : '未知'
          }
          if (['timeOfEntry', 'correctionTime'].includes(enlishKey)) {
            val = dayjs(val).format('YYYY年MM月DD日')
          }
          res.push(val)
          console.log(1111)
        })
        arr.push(res)
      })
      console.log(arr)
      return arr
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-container {
  .staff {
    width: 70px;
    height: 70px;
    border-radius: 50%;
  }
}

</style>
